import api from '../../../api/index';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsid: null,
    images: [],
    goodslist: null,
    evaluateImages:[
      'https://hxhealth.oss-cn-beijing.aliyuncs.com/f8e5ceabddcb43809bda819a4be2445fIMG_CMP_20231116_13522709.jpeg',
      'https://hxhealth.oss-cn-beijing.aliyuncs.com/jT8yDcOQOE7w0a4fe05485894d74ea0efb3568f0a335.jpeg',
      'https://hxhealth.oss-cn-beijing.aliyuncs.com/jT8yDcOQOE7w0a4fe05485894d74ea0efb3568f0a335.jpeg',
      'https://hxhealth.oss-cn-beijing.aliyuncs.com/jT8yDcOQOE7w0a4fe05485894d74ea0efb3568f0a335.jpeg',
      'https://hxhealth.oss-cn-beijing.aliyuncs.com/jT8yDcOQOE7w0a4fe05485894d74ea0efb3568f0a335.jpeg'
    ],
    star: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/shop/start.png',
    dizhidata: [],
    checkedAddress: {},
    show: false,
    radio: 0,
    totalNum: 1,
    deliveraddressList:[],
    showshop: false,
    value: 1,
    shopCarNum: 0,
    username3: '',
    totalPrice: 0,
    evaluatesData: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('onLoad')
    const toast = Toast.loading({
			// duration: 0, // 持续展示 toast
			forbidClick: true,
			message: '正在加载...',
			zIndex: 100000,
			position: 'top',
			selector: '#custom-selector'
		});
		this.setData({
			toast: toast
    });
    const {id} = options
    this.setData({
      goodsid: id 
    });
    this.loadDesic(id);
    this.evaluates(id)
    this.deliveraddressList()
  },
  showPopup() {
    this.setData({
      show: true 
    });
  },
  async getHealthServicer() {
    const actions = {
			data: {
				name: '',
        regioncode: '',
        roleids: '',
			}
		}
    const res = await api.get(`/api/hxhealth/servicer/shop`, actions)
    if (res && res.length > 0) {
		 	wx.navigateTo({
				url: `/healthCounseling/pages/detail/index?conversationID=${res[0].imuserid}`
			});
    }
  },
  /**
   * 跳转客服
   */
	goCustomer() {
		this.getHealthServicer()
	},
  onClose() {
    this.setData({ show: false });
  },
  onChange(event) {
    this.setData({
      totalNum: event.detail,
      totalPrice: event.detail * Number(this.data.goodslist.price)
    });
  },
  showPopupShop() {
    this.setData({
      value: 1,
      totalPrice: Number(this.data.goodslist.price)
    });
    this.setData({ showshop: true });
  },

  onCloseShop() {
    this.setData({ showshop: false });
  },
  gotoShoppingCart() {
    wx.navigateTo({
      url: '/shop/pages/shoppingcart/index',
    })
  },
  onChangeNum() {
    Toast.loading({ forbidClick: true });

    setTimeout(() => {
      Toast.clear();
      this.setData({ value });
    }, 500);
  },

  // 商品信息
  async loadDesic(id) {
    try {
      const res = await api.get(`/api/hxhealth/goods/load/${id}`);
      if(res && res.length > 0) {
        var images = res[0].images
        if (images.startsWith('[')) {
          var firstImageUrl = []
          var imagesArray = JSON.parse(images);
          for (let i = 0; i < imagesArray.length; i++) {
            firstImageUrl.push(imagesArray[i].file)
          }
          res[0].firstImageUrl = firstImageUrl;
        } else {
          var imageUrls = images.split(',');
          res[0].firstImageUrl = imageUrls;
        }
        console.log(res);
        res[0].desc = res[0].desc.replace(/<img(.*?)style="/g, '<img$1style="width: 100%; ');
        this.setData({
          goodslist: res[0],
          images: res[0].firstImageUrl
        });
      }
		} catch (e) {
			console.log('goodslist->', e);
			return null;
		}
  },
  generateStars: function (count) {
    const starImageUrl = "http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/shop/start.png";
    const starImages = [];
    for (let i = 0; i < count; i++) {
      starImages.push(starImageUrl);
    }
    return starImages;
  },
  // 商品评价
  async evaluates(id) {
    const actions = {
			data: {
        goodsid: id,
        // level: 1
			}
		}
    try {
      const res = await api.post('/api/hxhealth/goods/evaluates',actions);
      console.log('=======商品评价==============');
      console.log(res);
      if(res && res.length > 0) {
        res.forEach(item => {
          const imgListStr = JSON.parse(item.images)
          const list = []
          item.stars = this.generateStars(item.stars)
          if(imgListStr.images && imgListStr.images.length > 0) {
            imgListStr.images.forEach(img => {
              list.push(img.file)
            })
          }
          item.showImg = list
        })
        console.log(res);
        this.setData({
          evaluatesData: res
        })
      console.log(this.data.evaluatesData);
      }
		} catch (e) {
			console.log('loadDesic->', e);
			return null;
		}
  },
  onEvaluateClick(e) {
    console.log(e);
    wx.navigateTo({ url: `/shop/pages/evaluationmanagement/index?id=${this.data.goodslist.id}` });
  },
  // 获取收货地址列表
  async deliveraddressList() {
    console.log('deliveraddressList')
    const actions = {
			data: {
        name: '',
			}
		}
    try {
      const res = await api.post('/api/hxhealth/deliveraddress/list',actions);
      this.setData({
        radio: 0
      })
      if(res && res.length > 0) {
        const reRes = res.reverse()
        reRes.forEach((item, index) => {
          if (item.defau == '1') {
            this.setData({
              radio: index
            })
            return
          }
        })
        this.setData({
          dizhidata: reRes
        });
        this.setData({
          checkedAddress: this.data.dizhidata[this.data.radio],
        });
      } else {
        this.setData({
          dizhidata: []
        });
        this.setData({
          checkedAddress: {},
        });
      }
		} catch (e) {
			console.log('deliveraddressList->', e);
			return null;
		}
  },
  //收藏
  changeShoppingcollect() {
    try {
      api.get(`/api/hxhealth/goods/collect/${this.data.goodsid}`).then((res) => {
        console.log(res);
        this.loadDesic(this.data.goodsid)
      });
    } catch (e) {
      console.error(e);
    }
  },
  unchangeShoppingcollect() {
    try {
      api.get(`/api/hxhealth/goods/uncollect/${this.data.goodsid}`).then((res) => {
        console.log(res);
        this.loadDesic(this.data.goodsid)
      });
    } catch (e) {
      console.error(e);
    }
  },
  async getShopCarNum() {
    const res = await api.post('/api/hxhealth/shopcart/list')
    if(res) {
      this.setData({
        shopCarNum: res.length
      })
    }
  },
  // 加入购物车
  async onGoodsClick() {
    const actions = {
			data: {
        goodsamount: this.data.value,
        goodsid:this.data.goodslist.id
			}
		}
    try {
      const res = await api.post('/api/hxhealth/shopcart/save',actions);
      console.log(res);
      wx.showToast({
        title: '添加成功！',
        icon: 'none',
        duration: 3000
      });
      this.getShopCarNum()
		} catch (e) {
			console.log('deliveraddressList->', e);
			return null;
		}
  },
  async onClickButton() {
    if(this.data.dizhidata.length == 0) {
      wx.showToast({
        title: '请添加收货地址！',
        icon: 'none',
        duration: 3000
      });
      return false
    }
    var shopCartItems = [{
      goodsamount: this.data.totalNum,
      goodsid:this.data.goodslist.id,
    }]
    const actions = {
      data: {
        address: this.data.checkedAddress.address,
        addressregion: this.data.checkedAddress.addressregion,
        mobile: this.data.checkedAddress.mobile,
        receiver: this.data.checkedAddress.receiver,
        items: shopCartItems
      }
    }
    try {
      const res = await api.post('/api/hxhealth/shoporder/create',actions);
      console.log(res);
      console.log(res[0].code);
      this.setData({
        orderid: res[0].code
      });
      this.wxpay(res[0].code)
    } catch (e) {
      wx.showToast({
        title: e.faultstring,
        icon: 'none',
        duration: 3000
      });
      return null;
    }
  },
  wxpay(orderid) {   
    // let openid = wx.getStorageSync('openid')
    // 必须提供appId,userOrg,orderId,openId
    const actions = {
      data: {
        appId:'wxeed56b13879c5337',
        userOrg:'hongxing',
        // openid,
        orderid
      }
    }
    api.post('/api/hxhealth/shoporder/wxpay',actions).then((res) => {
      console.log(res);
      this.wxrequestPayment(res[0],orderid)
      // wx.showToast({
      //       title: '支付',
      //       icon: 'none',
      //       duration: 3000
      //     });
  });
  },
  goChangeAdress() {
    wx.navigateTo({ url: '/shop/pages/deliveraddress/index' });
  },
  onClose() {
    this.setData({
      checkedAddress: this.data.dizhidata[this.data.radio],
      show: false
     });
  },
  onChangeAddress(event) {
    this.setData({
      radio: event.detail,
    });
  },
  wxrequestPayment(result,orderid) {
    this.setData({
      result
    });
    let that = this
    wx.requestPayment({
      timeStamp: result.timeStamp,
      nonceStr: result.nonceStr,
      package: 'prepay_id='+result.prepayId,
      signType: 'MD5',
      paySign: result.paySign,
      success (res) { 
        console.log(res);
        console.log('支付 完成');
        wx.redirectTo({
          url: `/shop/pages/myordersuccess/index?orderid=${orderid}`
        })
      },
      fail (res) {
        console.log(res);
        console.log('支付失败');
        
        Dialog.confirm({
          cancelButtonTrext: '放弃',
          confirmButtonText: '继续付款',
          cancelButtonColor: 'dimgrey',
          confirmButtonColor: 'dodgerblue',
          message: '确认要放弃付款吗',
        })
          .then(() => {
            that.wxpay(that.data.order)
          })
          .catch(() => {
            that.setData({ showshop: false });
            console.log('继续放弃支付');
          });
       }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getShopCarNum()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})